package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import com.atguigu.gulimall.member.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(UserRegisterVo userRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setMobile(userRegisterVo.getPhone());
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(memberLevelEntity.getId());

        // 为了保证用户名和密码的唯一性和手机号是否唯一 , 该方法没返回值 ,  采用异常机制
        checkPhoneUnique(userRegisterVo.getPhone());
        checkUsermnameUnique(userRegisterVo.getUsername());
        memberEntity.setUsername(userRegisterVo.getUsername());
        /**
         *  密码需要进行加密存储, 分为可逆加密和不可逆加密
         */
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //加密密码
        String encode = passwordEncoder.encode(userRegisterVo.getPassword());
        memberEntity.setPassword(encode);


        baseMapper.insert(memberEntity);
    }

    /**
     * 检查手机号和邮箱的唯一性
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUsermnameUnique(String username) throws UsernameExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        List<MemberEntity> memberEntities = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("username", userLoginVo.getUsername())
                .or().eq("mobile", userLoginVo.getUsername()));
        if (memberEntities != null && memberEntities.size() > 0) {
            //存在账号,  校验密码
            boolean matches = passwordEncoder.matches(userLoginVo.getPassword(), memberEntities.get(0).getPassword());
            if (matches) {
                // 登录成功
                return memberEntities.get(0);
            } else {
                //密码输入错误
                return null;
            }
        } else {
            //登录失败
            return null;
        }

    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) {
        List<MemberEntity> memberEntities = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("uid", socialUser.getUid()));
        if (memberEntities.size() > 0 && memberEntities != null) {
            // 登录
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setUid(socialUser.getUid());
            memberEntity.setExpires(socialUser.getExpires_in());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setId(memberEntities.get(0).getId());
            baseMapper.updateById(memberEntity);
            MemberEntity memberEntity1 = memberEntities.get(0);
            memberEntity1.setUid(socialUser.getUid());
            memberEntity1.setExpires(socialUser.getExpires_in());
            memberEntity1.setAccessToken(socialUser.getAccess_token());
            return memberEntity1;
        } else {
            //注册
            MemberEntity memberEntity = new MemberEntity();
            //查询当前用户微博的用户信息https://api.weibo.com/2/users/show.json
            HashMap<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询用户成功
                    JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                    memberEntity.setNickname(jsonObject.getString("name"));
                    memberEntity.setGender(jsonObject.getString("gender").equals("m") ? 1 : 0);
                }
            } catch (Exception e) {
            }
            //即使远程调用查询用户的信息失败 也不要紧, 继续让用户登录
            memberEntity.setUid(socialUser.getUid());
            memberEntity.setExpires(socialUser.getExpires_in());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            baseMapper.insert(memberEntity);
            return memberEntity;
        }
    }

}